package com.rbac.web.controller;

import com.rbac.web.exception.ApplicationException;
import com.rbac.web.model.PageResult;
import com.rbac.web.model.User;
import com.rbac.web.model.UserContext;
import com.rbac.web.model.req.UserAddReq;
import com.rbac.web.model.req.UserGetListReq;
import com.rbac.web.model.res.UserGetListRes;
import com.rbac.web.model.res.UserGetOneRes;
import com.rbac.web.service.ISysParamCodeService;
import com.rbac.web.service.IUserService;
import com.rbac.web.service.IUserTokenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author gengaoliu
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Tag(name = "用户管理", description = "刘澳港")
@Slf4j
public class UserController {

  private final IUserService userService;
  private final IUserTokenService tokenService;

  private final ISysParamCodeService sysParamCodeService;

  @PostMapping("/save")
  @Operation(summary = "添加用户")
  public void save(@Schema @RequestBody @Validated UserAddReq req) {
    User user = UserContext.get();
    User domain = req.toDomain();
    domain.setCreatedBy(user.getId());
    domain.setUpdatedBy(user.getId());
    userService.save(domain);
  }

  @GetMapping
  @Operation(summary = "获取用户列表")
  public PageResult<UserGetListRes> getList(@ParameterObject UserGetListReq req) {
    return req.execute(req.toPageV0(), req.getName(), userService);
  }

  @PutMapping("/{id}")
  @Operation(summary = "修改用户")
  public void update(@PathVariable Integer id, @RequestBody UserAddReq addReq) {
    User user = addReq.toDomain();
    user.setId(id);
    userService.updateById(user);
  }

  @GetMapping("/{id}")
  @Operation(summary = "查看账号详情")
  public UserGetOneRes getOneRes(@PathVariable Integer id) {
    return Optional.ofNullable(userService.findById(id))
        .map(UserGetOneRes::from)
        .orElseThrow(() -> ApplicationException.createException("不存在的账户"));
  }

  @DeleteMapping("/{id}")
  @Operation(summary = "删除账号")
  public void deleteById(@PathVariable Integer id) {
    tokenService.deleteUserRole(id);
    userService.deleteById(id);
  }

  @GetMapping("/list")
  @Operation(summary = "账号列表-不分页")
  public List<UserGetListRes> getList() {
    log.info("====>测试SysParamCode");
    String redisConf = sysParamCodeService.getRedisConf("test", "test", "test");
    log.info("===>值为：{}", redisConf);
    return userService.selectList().stream().map(UserGetListRes::from).toList();
  }
}
